package top.tagao.kafka.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.record.FileRecords;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.*;

/**
 * @author fu-xiao-liu
 * @Date 2022/8/30 17:47
 */
public class CustomConsumerSeekTime {
    public static void main(String[] args) {
        //0.配置信息
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "47.106.86.64:9092");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "test");

        //1.创建消费者
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);
        ArrayList<String> topic = new ArrayList<>();
        topic.add("first");
        kafkaConsumer.subscribe(topic);

        //A .获取分区信息
        Set<TopicPartition> assignment = new HashSet<>();
        while (assignment.size() == 0) {
            kafkaConsumer.poll(Duration.ofSeconds(100));
            assignment = kafkaConsumer.assignment();
        }

        //B. 设置不同分区的时间
        HashMap<TopicPartition, Long> timestamp = new HashMap<>();
        for (TopicPartition topicPartition : assignment) {
            timestamp.put(topicPartition, System.currentTimeMillis() - 24 * 3600 * 1000);
        }

        //C. 通过消费者获取分区的 某时间的offset起点
        Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes = kafkaConsumer.offsetsForTimes(timestamp);

        //D. 通过offsetsForTime 得到 主题-分区 的 一天前的 offset起点
        for (TopicPartition tp : assignment) {
            kafkaConsumer.seek(tp, offsetsForTimes.get(tp).offset());
        }


        //2.消费信息
        while (true) {
            ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofSeconds(1));
            records.forEach(record -> {
                System.out.println(record);
            });
        }

        //3.关闭

    }

}
